<?php 
   require_once 'database.php';
   header("content-type:application/json");
   $objReturn = array();
   
   //save the project id
   $project = $_POST['project_id'];

   
   $iterationLength = null;
   $start = null;

   $fullProject = mysql_query("SELECT * FROM project WHERE project_id= '$project'",$dbLocalhost)
      or die("Problem reading table: " . mysql_error());
    while($row = mysql_fetch_array($fullProject)) {
       $iterationLength = $row['iteration_length'];
       $start = $row['end_date'];
    	
   }
   //The new iteration date will begin when the old iteration ends (which is tracked by the project end date)

   $end = date('Y-m-d',strtotime($start." + ".$iterationLength." days"));
   
   
   $insert= "INSERT INTO iteration(project_id, start_date, end_date) VALUES ('$project', '$start', '$end')";
   $createIteration = mysql_query($insert);
   
   //update project
   $updateProject = mysql_query("UPDATE project SET end_date='$end' WHERE project_id='$project'");
   $iterationList =  mysql_query("SELECT iteration_id FROM iteration WHERE project_id= '$project' AND end_date = '$end'", $dbLocalhost);
   $iteration = null;
   
   while($row = mysql_fetch_array($iterationList)) {
   	$iteration = $row['iteration_id'];
   	 
   }   
   
   $objReturn['code'] = 'SUCCESS';
   $objReturn['iteration_id'] = $iteration;   
   echo json_encode($objReturn);
?>
